//
//  OpenSDK_LoginMobileView.m
//  OpenSDK
//
//  Created by 涂俊 on 2018/7/12.
//  Copyright © 2018年 WYHT. All rights reserved.
//

#import "OpenSDK_LoginMobileView.h"
#import "OpenSDK_SmsView.h"
#import "OpenSDK_LocalRecord.h"
#import "OpenSDK_LoginLoadingView.h"
#import "OpenSDK_LoginMoreView.h"
#import "OpenSDK_Toast.h"
#import "OpenSDK_PullDownView.h"
#import "OpenSDK_CountryCell.h"
#import "OpenSDK_DataKeys.h"
#import "OpenSDK_LoginProtocol.h"

#import "OpenSDK_UIManager.h"
#import "OpenSDK_LoginManager.h"
#import "OpenSDK_DataManager.h"
#import "OpenSDK_ImageUtil.h"

#import "OpenSDK_UIUtil.h"

#import <objc/runtime.h>
#import "LocalizationManager.h"
#import "OpenSDK_UserAgreementView.h"

#import "OPKTracking.h"
#import "OPKCoreConfiguration.h"

@interface OpenSDK_LoginMobileView () <UITableViewDataSource>
@property (unsafe_unretained, nonatomic) IBOutlet OpenSDK_UserAgreementView *userAgreementView;
@property (unsafe_unretained, nonatomic) IBOutlet NSLayoutConstraint *contentViewHeightConstraint;
@property (unsafe_unretained, nonatomic) IBOutlet NSLayoutConstraint *bgImageViewHeightConstraint;

@end

@implementation OpenSDK_LoginMobileView

{
    UIButton *countryBtn;
}

static CGFloat loginBtnWidth = 90;
static CGFloat loginBtnHeight = 25;

#pragma mark - 生命周期函数
- (void)viewDidLoad {
    NSLog(@"%@,%@",NSStringFromClass([self class]), NSStringFromSelector(_cmd));
    [super viewDidLoad];
    _bgView.backgroundColor = UIColor.whiteColor;
    _bgView.layer.cornerRadius = 10;
    _bgView.layer.masksToBounds = true;
    // Do any additional setup after loading the view.
    
    // 输入法上移，相对于bgView
    self.keyboardExtraMargin = 30;
    
    // 如果指定logo图片，则设置对应logo图片
    NSString *logoImageName = [[[[NSBundle mainBundle] infoDictionary] objectForKey:OpenSDK_CONFIG] objectForKey:OpenSDK_LOGO];
    if (logoImageName != nil && logoImageName.length > 0) {
        // 如果没有指定logo图片，则使用默认logo图片
        UIImage *image = [UIImage imageNamed:logoImageName];
        if (image != nil) {
            [self.logoImgView setImage:image];
        }
    }
    
    // 输入框内容缩进
    self.mobileInputView.delegate = self;// 添加输入框监听
    self.mobileInputView.edgeInsets = UIEdgeInsetsMake(0, 10, 0, 10);
    if (self.inputMobile != nil) {
        self.mobileInputView.text = self.inputMobile;
    }
    // 输入框左边是国家区号按钮
    countryBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, self.mobileInputView.frame.size.height)];
    [countryBtn setImage:[UIImage imageNamed:@"op_icon_history"] forState:UIControlStateNormal];
    countryBtn.titleLabel.font = [UIFont systemFontOfSize: 12.0];
    [countryBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [countryBtn addTarget:self action:@selector(didClickCountryBtn:) forControlEvents:UIControlEventTouchUpInside];
    // 加载本地保存的当前国家区号
    if([[OpenSDK_LocalRecord getInstance] getLocalValueForKey:OpenSDK_L_COUNTRY_CODE]!=nil) {
        [self resetCountryCodeInfo];
    } else {
        NSString *countryNumber = [[[OpenSDK_DataManager getInstance] getCountryCodeFromCurMachine] objectForKey:OpenSDK_S_COUNTRY_NUMBER];
        [countryBtn setTitle:countryNumber forState:UIControlStateNormal];
    }
    // 文字左，图片右
    CGFloat imageWidth = countryBtn.imageView.bounds.size.width + 7;
    CGFloat labelWidth = countryBtn.titleLabel.bounds.size.width + 7;
    countryBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
    countryBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth, 0, imageWidth);
    // 添加到输入框中
    [self.mobileInputView setEdgeView:countryBtn width:60 horizontalPadding:0 verticalPadding:0 isLeft:YES];
    
    // 点击背景，收起输入法
    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didHideKeyboard:)]];
    [self.bgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didHideKeyboard:)]];
    
    
    if (self.navigationController.viewControllers.count > 1 && !_cantBack) {
        // 从其他界面跳转过来
        self.backBtn.hidden = NO;
        self.closeBtn.hidden = YES;
    } else {
        // 本身是第一个界面
        self.backBtn.hidden = YES;
        self.closeBtn.hidden = NO;
    }
    
    //其他登录方式的显示
    [[OpenSDK_UIManager getInstance] handleOtherLoginTypesWithButton:self.otherLoginBg curLoginType:OpenSDK_S_DYNAMIC];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 设置对勾按钮状态
    [_userAgreementView.agreeButton setSelected:[OpenSDK_DataManager getInstance].contranctChecked];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [[OPKTracking shared] pageView:OPKPageLoginMobile];
}

// 用户协议相关检查
- (BOOL)contranctChecked {
    if ([OpenSDK_DataManager getInstance].showContranct == NO) {
        return YES;
    }
    // 是否已经同意用户协议
    if (_userAgreementView.agreeButton.isSelected == NO) {
        [[[OpenSDK_iToast makeText:@"请先同意相关政策条款再登录"] setDuration:2000] show];
        return NO;
    }
    return YES;
}

#pragma mark - [私有方法] 刷新选择的国家区号
-(void) resetCountryCodeInfo {
    if([[[OpenSDK_DataManager getInstance] countryCodeInfo] count]==0)
        return;
    NSString *localCountryCode=[[OpenSDK_LocalRecord getInstance] getLocalValueForKey:OpenSDK_L_COUNTRY_CODE];
    NSMutableDictionary *dic;
    NSString *countryNumber;
    for( int i=0; i<[[OpenSDK_DataManager getInstance] countryCodeInfo].count; i++) {
        dic=[[[OpenSDK_DataManager getInstance] countryCodeInfo] objectAtIndex:i];
        if([[dic objectForKey:OpenSDK_S_COUNTRY_CODE] isEqualToString:localCountryCode]) {
            countryNumber=[dic objectForKey:OpenSDK_S_COUNTRY_NUMBER];
        }
    }
    if(countryNumber==nil) {
        localCountryCode=[[[[OpenSDK_DataManager getInstance] countryCodeInfo] objectAtIndex:0] objectForKey:OpenSDK_S_COUNTRY_CODE];
        countryNumber=[[[[OpenSDK_DataManager getInstance] countryCodeInfo] objectAtIndex:0] objectForKey:OpenSDK_S_COUNTRY_NUMBER];
        [[OpenSDK_LocalRecord getInstance] saveData:OpenSDK_L_COUNTRY_CODE value:localCountryCode];
    }
    [countryBtn setTitle:countryNumber forState:UIControlStateNormal];
}

#pragma mark - tableview回调
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[OpenSDK_DataManager getInstance] countryCodeInfo].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableDictionary *dic=[[[OpenSDK_DataManager getInstance] countryCodeInfo] objectAtIndex:indexPath.row];
    OpenSDK_CountryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OpenSDK_CountryCell" forIndexPath:indexPath];
    [cell.layer setBorderWidth:0.5];
    [cell.layer setBorderColor:[UIColor colorWithRed:202/255.0 green:202/255.0 blue:202/255.0 alpha:1].CGColor];
    cell.nameView.text = [dic objectForKey:OpenSDK_S_COUNTRY_NAME];
    cell.numberView.text = [dic objectForKey:OpenSDK_S_COUNTRY_NUMBER];
    return cell;
}

#pragma mark - 按钮监听
- (void)didClickCountryBtn:(id)sender {
    //收起键盘
    [self didHideKeyboard:sender];
    
    OpenSDK_PullDownView *menuView = [OpenSDK_PullDownView pullMenuAnchorView:sender
                                                                tableDelegate:self
                                                                    menuWidth:self.mobileInputView.frame.size.width
                                                                  cellNibName:@"OpenSDK_CountryCell"
                                                          cellReuseIdentifier:@"OpenSDK_CountryCell"];
    menuView.menuCellHeight = self.mobileInputView.frame.size.height;
    menuView.menuMaxHeight = 3 * self.mobileInputView.frame.size.height;//默认显示3格
    menuView.place = AnchorPlaceLeft;
    menuView.blockSelectedMenu = ^(NSInteger menuRow) {
        // 点击国家区号
        NSLog(@"click----->%ld", (long)menuRow);
        NSMutableDictionary *dic=[[[OpenSDK_DataManager getInstance] countryCodeInfo] objectAtIndex:menuRow];
        NSString *curCountryCode=[dic objectForKey:OpenSDK_S_COUNTRY_CODE];
        [[OpenSDK_LocalRecord getInstance] saveData:OpenSDK_L_COUNTRY_CODE value:curCountryCode];
        [self resetCountryCodeInfo];
    };
    [menuView show:NO];
}



- (IBAction)didClickNextBtn:(id)sender {
    
    //收起键盘
    [self didHideKeyboard:sender];
    
    // 统计
    [[OPKTracking shared] event:OPKEventLoginMobileNext];
    
    NSString *mobile = self.mobileInputView.text;
    if (mobile == nil || mobile.length == 0) {
        [[[OpenSDK_iToast makeText:@"手机号不能为空"] setDuration:2000] show];
        return;
    }
    if ([countryBtn.titleLabel.text containsString:@"+86"] &&
        mobile.length != 11){
        [[[OpenSDK_iToast makeText:@"请输出正确的手机号"] setDuration:2000] show];
        return;
    }
    
    // 是否已经同意用户协议
    if ([self contranctChecked] == NO) {
        return;
    }
    
    // 跳转到验证码界面
    UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginMain" bundle:nil];
    OpenSDK_SmsView *vc = (OpenSDK_SmsView *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_SmsView"];
    vc.mobile = mobile;
    vc.isBind = NO;
    [self.navigationController pushViewController:vc animated:NO];
}

- (void)didClickGuestBtn:(id)sender {
    
    //收起键盘
    [self didHideKeyboard:sender];
    
    // 是否已经同意用户协议
    if ([self contranctChecked] == NO) {
        return;
    }
    
    // 先弹出loading框
    UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginMain" bundle:nil];
    OpenSDK_LoginLoadingView *vc = (OpenSDK_LoginLoadingView *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_LoginLoadingView"];
    vc.accoutnName = @"游客";
    [self.navigationController pushViewController:vc animated:NO];
    
    // 再调用登录接口
    [[OpenSDK_LoginManager getInstance] loginWithGuest:^(BOOL result, OpenSDK_AccountRecord *account, long errorNo, NSString *err) {
        if (!result) {
            // 登录失败
            [[[OpenSDK_iToast makeText:err] setDuration:2000] show];
        }
        [vc loginResultCallback:result account:account];
    }];
}

- (void)didClickMailBtn:(id)sender {
    
    //收起键盘
    [self didHideKeyboard:sender];

    // 是否已经同意用户协议
    if ([self contranctChecked] == NO) {
        return;
    }

    // 跳转到邮箱登录界面
    [[OpenSDK_UIManager getInstance] showNextUIWithStoryBoard:@"LoginMain" withVCId:@"OpenSDK_LoginMailView"];
}


- (void)didClickOtherSDKBtn:(id)sender {
    //收起键盘
    [self didHideKeyboard:sender];
    
    // 统计
    [[OPKTracking shared] event:OPKEventLoginOther];
    
    // 是否已经同意用户协议
    if ([self contranctChecked] == NO) {
        return;
    }
    
    // 获取登录类型
    NSString * loginType = objc_getAssociatedObject(sender, @"loginType");
    id<OpenSDK_LoginProtocol> sdkClass =  [[OpenSDK_DataManager getInstance].supportSDKServerNames valueForKey:loginType];
    
    // 先弹出loading框
    UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"LoginMain" bundle:nil];
    OpenSDK_LoginLoadingView *vc = (OpenSDK_LoginLoadingView *) [loginStoryboard instantiateViewControllerWithIdentifier:@"OpenSDK_LoginLoadingView"];
    vc.accoutnName = [sdkClass getDisplaySdkName];
    [self.navigationController pushViewController:vc animated:NO];
    
    // 再调用第三方登录接口
    [[OpenSDK_LoginManager getInstance] loginWithPlatform:loginType delegate:^(BOOL result, OpenSDK_AccountRecord *account, long errorNo, NSString *err) {
        if (!result) {
            // 登录失败
            [[[OpenSDK_iToast makeText:err] setDuration:2000] show];
        }
        [vc loginResultCallback:result account:account];
    }];
}


- (void)didClickMoreBtn:(id)sender {
    //收起键盘
    [self didHideKeyboard:sender];
    
    // 跳转到更多登录界面
    [[OpenSDK_UIManager getInstance] showNextUIWithStoryBoard:@"LoginMain" withVCId:@"OpenSDK_LoginMoreView"];
}
- (IBAction)moreLogin:(UIButton *)sender {
    //收起键盘
    [self didHideKeyboard:sender];
    
    BOOL contranctChecked = _userAgreementView.agreeButton.isSelected == NO ? NO : YES;
    [[OpenSDK_UIManager getInstance] handleOtherLoginMethodWithCurLoginType:OpenSDK_S_DYNAMIC contranctChecked:contranctChecked];

    // 跳转到更多登录界面
//    [[OpenSDK_UIManager getInstance] showNextUIWithStoryBoard:@"LoginMain" withVCId:@"OpenSDK_LoginMoreView"];
    //[[OpenSDK_UIManager getInstance] showViewControllerWithSBId:@"LoginMain" vcid:@"OpenSDK_LoginMoreView"];
}

- (IBAction)didClickBackBtn:(id)sender {
    [[OpenSDK_UIManager getInstance] goBack];
}

- (IBAction)didClickCloseBtn:(id)sender {
    //    [self dismissViewControllerAnimated:NO completion:nil];
    [[OpenSDK_UIManager getInstance] closeUI];
    [[OpenSDK_LoginManager getInstance] sendLoginCacelEvent];
}


@end
